$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange }) {
  /* 0516 正式未添加的功能扩展
      getLcbjhHkTotalAmt
      getXshtInPay
      getProjectSybyTotalAmt
      getFbyfdTotalAmtByPhidPc
      getSjcztbTotalAmt
   */
  const mstform = $NG.getCmpApi("p_form_servicee_qs_m")
  const dgrid = $NG.getCmpApi("p_form_servicee_qs_d")
  // init
  if (page.oType == 'add' || page.oType == 'edit') {
    getPtInfoByPhid()
    getCntMInfoByPhid()
    getLcbjhHkTotalAmt()
    getXshtInPay()
    getFbyfdTotalAmtByPhidPc()
    getSjcztbTotalAmt()
    // cnt
    getProjectSybyTotalAmt()
    getCntCount("p_form_servicee_qs_m", "u_cnt_name", cntMain)
  }
  // 表头监听器
  // 防止各种表头赋值无法控制异步同步导致不顺序执行取数错误情况
  const headValueEvent = (() => {
    const obj = {};
    const fields = [
      'u_htxe', 'u_yhje', 'u_yhkje', 'u_yhwhje', 'u_cgyfje', 'u_fbyfje', 'u_czby',
      'u_dqwcl', 'u_srqrje', 'u_srce', 'u_ywghs', 'u_ywgmll', 'u_mllzj',
      'u_zjl', 'u_ycztwg', 'u_ycztwgmll', 'u_ychtezj', 'u_ychtwcl', 'u_yjzjl'
    ];
    // getAll 方法
    Object.defineProperty(obj, 'getAll', {
      value: function () {
        let map = {}
        for (let key of fields) {
          map[key] = this['_' + key]
        }
        return map
      },
      writable: true,
      enumerable: false,
      configurable: false
    });
    // sumAmt 方法
    Object.defineProperty(obj, 'sumAmt', {
      value: function () {
        this._u_yhwhje = this._u_yhje - this._u_yhkje // 应未回款金额
        this._u_srce = this._u_yhkje - this._u_srqrje // 收入差额
        this._u_dqwcl = this.u_srqrje ? this.u_srqrje / this._u_htxe : 0
        const _map = this.getAll()
        $NG.updateState((updater) => {
          updater.data.p_form_servicee_qs_m.setProps({ ..._map })
        })
      },
      writable: true,
      enumerable: false,
      configurable: false
    });


    for (const field of fields) {
      const privateKey = `_${field}`;
      // 建立私有变量
      Object.defineProperty(obj, privateKey, {
        value: 0,
        writable: true,
        enumerable: false,
        configurable: false
      });
      // 建立公有变量
      Object.defineProperty(obj, field, {
        enumerable: true,
        configurable: false,
        get() {
          return obj[privateKey];
        },
        set(val) {
          obj[privateKey] = (Number(val) || 0);
          obj.sumAmt();
        }
      });
    }

    return obj;
  })();

  // 入口
  function cntMain() {
    getProjectSybyTotalAmt()
  }

  function phidPcMain() {
    getPtInfoByPhid()
    getCntMInfoByPhid()
    getLcbjhHkTotalAmt()
    getXshtInPay()
    getFbyfdTotalAmtByPhidPc()
    getSjcztbTotalAmt()
  }

  useValuesChange(({ args }) => {
    phidPcMain()
  }, "p_form_servicee_qs_m.phid_pc")

  useValuesChange(({ args }) => {
    cntMain()
  }, "p_form_servicee_qs_m.u_cnt_name")

  useUpdateRows(() => {
    sumAmt()
  }, "p_form_servicee_qs_d")

  // 获取项目信息
  function getPtInfoByPhid() {
    if (mstform.getItem("phid_pc").getValue()) {
      $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        $NG.updateState((updater) => {
          updater.data.p_form_servicee_qs_m.setProps({
            //项目编码
            u_pc_no: datas.pc_no,
            //项目金额
            approx_contract_fc: datas.approx_contract_fc,
            //计划开工日期
            start_date: datas.start_date,
            //计划完工日期
            end_date: datas.end_date,
            u_gcgk: datas.descript,
            //售前顾问
            u_sqgw: {
              value: datas.user_sqgw_phid,
              label: datas.user_sqgw_name,
            },
            //项目经理
            phid_emp: {
              value: datas.project_manager_phid,
              label: datas.project_manager_name,
            },
            //事业部
            u_division: {
              value: datas.division_phid,
              label: datas.division_name,
            },
            //组织
            phid_org: {
              value: datas.phid_org_phid,
              label: datas.phid_org_name,
            },
            //区域中心
            u_regional_center: {
              value: datas.regional_center_phid,
              label: datas.regional_center_name,
            },
            //产品线
            u_product_line: {
              value: datas.midwife_phid,
              label: datas.midwife_name,
            },
            //客户名称
            customer: {
              value: datas.customer_id,
              label: datas.customer_name,
            },
            //部门
            u_dept: {
              value: datas.dept_phid,
              label: datas.dept_name,
            },
            //项目类型
            u_pc_type: {
              value: datas.type_phid,
              label: datas.type_name,
            },
            //项目预算组织编码
            budget_org_code: datas.budget_org_no,
            //项目预算组织
            budget_org_phid: {
              value: datas.budget_org_phid,
              label: datas.budget_org_name,
            },
          });
        });
      });
    }
  }

  // 获取合同信息
  function getCntMInfoByPhid(params) {
    if (!mstform.getItem("u_cnt_name").getValue()) return
    $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt_name").getValue() }, function (res) {
      const datas = JSON.parse(res.data)[0].extendObjects;
      // console.log(datas);

      headValueEvent.u_htxe = datas.cnt_sum_vat_fc

      $NG.updateState((updater) => {
        updater.data.p_form_servicee_qs_m.setProps({
          u_cnt_no: datas.pcm_no, //合同编号
          start_dt: datas.start_dt, //约定开工时间
          end_dt: datas.end_dt, //约定完工时间
          u_qdmll: datas.user_qdmllb,// 签单毛利
          u_cshte: datas.init_cnt_amt,// 初始合同额
          u_total_cnt_amt_vat: datas.cnt_sum_vat_fc, //合同金额
          u_htxe: datas.cnt_sum_vat_fc, //合同现额（未税）
          //产品线
          user_product_line: {
            value: datas.midwife_phid,
            label: datas.midwife_name,
          },
          //合同类型
          u_cnt_type: {
            value: datas.pct_id,
            label: datas.pct_name,
          },
          //甲方单位
          u_customer: {
            value: datas.customer_id,
            label: datas.customer_name,
          },
          //乙方单位
          supply: {
            value: datas.supply_id,
            label: datas.supply_name,
          },
          //发票类型
          u_invoice_type: {
            value: datas.invoice_type_phid,
            label: datas.invoice_type_name,
          },
          //购方信息（客户信息）（收票单位信息）
          //单位名称
          tick_id: {
            value: datas.tick_id,
            label: datas.tick_name,
          },
          //单位编码
          tick_no: datas.tick_no,
          //社会信用代码
          tick_unisocialcredit: datas.tick_unisocialcredit,
          //单位地址
          tick_taxaddress: datas.tick_taxaddress,
          //联系电话
          tick_taxtelephone: datas.tick_taxtelephone,
          //银行名称
          tick_taxbankid: {
            value: datas.tick_taxbankid,
            label: datas.tick_taxbankname,
          },
          //银行账号
          tick_taxaccountno: datas.tick_taxaccountno,
          //销方信息（供应商信息）（开票单位信息）
          //单位名称
          inv_id: { value: datas.inv_id, label: datas.inv_name },
          //单位编码
          inv_no: datas.inv_no,
          //社会信用代码
          inv_unisocialcredit: datas.inv_unisocialcredit,
          //单位地址
          inv_taxaddress: datas.inv_taxaddress,
          //联系电话
          inv_taxtelephone: datas.inv_taxtelephone,
          //银行名称
          inv_taxbankid: {
            value: datas.inv_taxbankid,
            label: datas.inv_taxbankname,
          },
          //银行账号
          inv_taxaccountno: datas.inv_taxaccountno,
        });
      });
    });
  }

  function sumAmt() {
    const rows1 = dgrid.getRows()
    let u_ycztwg = 0
    rows1.forEach(item => {
      u_ycztwg += (Number(item.u_ycztwg) || 0)
    })

    headValueEvent.u_zmje = u_ycztwg
  }

  // 获取里程碑计划回款明细的应回款金额
  function getLcbjhHkTotalAmt() {
    const phid_pc = mstform.getItem("phid_pc").getValue()
    if (!phid_pc) return
    $NG.execServer("getLcbjhHkTotalAmt", { phid_pc }, (res) => {
      if (res.count == 0) return
      const _data = JSON.parse(res.data)[0].extendObjects
      window._catch_lcb_hk_totalAmt = _data.yhk_total_amt

      // 赋值应汇款金额
      page.oType == "add" && (headValueEvent.u_yhje = _data.yhk_total_amt)
    })

  }

  // 获取销售合同收款汇总值
  function getXshtInPay() {
    const phid_pc = mstform.getItem("phid_pc").getValue()
    if (!phid_pc) return
    $NG.execServer("getXshtInPay", { phid_pc }, (res) => {
      if (res.count == 0) return
      const _data = JSON.parse(res.data)[0].extendObjects
      headValueEvent.u_yhkje = _data.total_amt
    })
  }

  // 获取项目收入报验相关金额
  function getProjectSybyTotalAmt() {
    const cnt = mstform.getItem("u_cnt_name").getValue()
    if (!cnt) return
    const _data = JSON.parse(res.data)[0].extendObjects
    headValueEvent.u_srqrje = _data.total_amt
  }

  // 分包应付单本期应付金额
  function getFbyfdTotalAmtByPhidPc() {
    const phid_pc = mstform.getItem("phid_pc").getValue()
    if (!phid_pc) return
    $NG.execServer("getFbyfdTotalAmtByPhidPc", { phid_pc }, (res) => {
      if (res.count == 0) return
      const _data = JSON.parse(res.data)[0].extendObjects
      headValueEvent.u_fbyfje = _data.bcsq_total_amt
    })
  }

  // 获取实际产值填报
  function getSjcztbTotalAmt() {
    const phid_pc = mstform.getItem("phid_pc").getValue()
    if (!phid_pc) return
    $NG.execServer("getSjcztbTotalAmt", { phid_pc }, (res) => {
      if (res.count == 0) return
      const _data = JSON.parse(res.data)[0].extendObjects
      headValueEvent.u_czby = _data.total_amt
    })
  }
})


//获取合同数量
function getCntCount(table, key, fun) {
  if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
  $NG.execServer(
    "getCntCount",
    {
      type: 1,
      phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue(),
    },
    (res) => {
      //   console.log(res, "count");
      switch (res.count) {
        case 0:
          return;
        case 1:
          const datas = JSON.parse(res.data)[0].extendObjects;
          const temp_map = {};
          temp_map[key] = datas.phid;
          temp_map[`${key}_EXName`] = datas.bill_name;
          $NG.updateState((updater) => {
            updater.data[table].setProps({
              ...temp_map,
            });
            setTimeout(() => {
              if (fun) {
                fun();
              }
            }, 200);
          });
      }
    }
  );
}